<template>
  <div class="login-bg">
    <div class="login-row">
      <!-- 系统标题 -->
      <div class="login-title">
        {{ $t($config.system.APP_NAME) }}
      </div>
      <!-- 登录表单 -->
      <el-form ref="userLoginForm" :model="loginForm" :rules="rules" hide-required-asterisk class="login-form">
        <!-- 用户名 -->
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            clearable
            maxlength="50"
            placeholder="Please input a username"
            :prefix-icon="UserFilled"
            @keyup.enter="submitLogin"
          />
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            show-password
            maxlength="50"
            placeholder="Please input a password"
            :prefix-icon="Lock"
            @keyup.enter="submitLogin"
          />
        </el-form-item>
        <!-- 验证码 -->
        <!-- <el-form-item prop="kaptcha">
          <el-input
            ref="kaptchaInput"
            v-model="loginForm.kaptcha"
            maxlength="4"
            style="width: 50%"
            placeholder="请输入验证码"
            @keyup.enter="submitLogin"
          >
            <template #prefix>
              <el-icon style="height: inherit">
                <Crop />
              </el-icon>
            </template>
          </el-input>
          <img
            v-if="captchaImg"
            class="codeimg"
            :src="captchaImg"
            alt=""
            @click="getCaptchaImg"
          >
        </el-form-item> -->
        <!-- 记住密码 -->
        <el-form-item class="remember">
          <el-checkbox
            v-model="loginForm.rememberme"
            label="Remember password"
            size="large"
            title="Valid for 90 days"
          />
        </el-form-item>
      </el-form>
      <!-- 登录按钮 -->
      <el-button type="primary" class="login-btn" @click="submitLogin"> login </el-button>
    </div>
    <!-- 页脚 -->
    <el-footer v-if="$config.system.FOOTER.SHOW" :class="{ beian: $config.system.BEIAN }">
      <bottom-footer :beian="$config.system.BEIAN" />
    </el-footer>
  </div>
</template>

<script lang="ts" setup>
/**
 * @author yinyuejia
 * @file 登录页面
 * @des
 */
import { ElLoading } from 'element-plus';
import 'element-plus/es/components/loading/style/css';
import { reactive, ref } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import { UserFilled, Lock } from '@element-plus/icons-vue';
import authApi from '@/apis/auth';
import { routerToMenu } from '@/utils/tool';
import BottomFooter from '@/components/Layout/BottomFooter.vue';
import i18n, { setI18nLanguage } from '@/locale';

const store = useStore();
const router = useRouter();
const loginForm = reactive({
  username: store.state.user.rememberme.username,
  password: store.state.user.rememberme.password,
  // kaptcha: '',
  rememberme: !!store.state.user.rememberme.username,
  // signature: '',
});

const rules = reactive({
  username: [
    {
      required: true,
      message: 'User name cannot be empty',
      trigger: 'change',
    },
  ],
  password: [
    {
      required: true,
      message: 'Password cannot be empty',
      trigger: 'change',
    },
  ],
  // kaptcha: [
  //   {
  //     required: true,
  //     message: '验证码不能为空',
  //     trigger: 'change',
  //   },
  // ],
});
const userLoginForm: any = ref(null);
// const kaptchaInput: any = ref(null);
// const captchaImg: any = ref(null);
// if (loginForm.rememberme) {
//   onMounted(() => {
//     kaptchaInput.value.focus();
//   });
// }
// // 获取验证码
// const getCaptchaImg = function () {
//   // 重置值
//   captchaImg.value = null;
//   authApi.getKaptcha().then((d: any) => {
//     // 如果请求正常返回
//     if (!!d) {
//       captchaImg.value = `data:image/png;base64,${d.img}`;
//       loginForm.signature = d.signature;
//     }
//   });
// };
// 获取用户信息
const getUserInfo = function () {
  return authApi
    .getUserInfo()
    .then((d: any) => {
      if (!!d && d.code === 200) {
        // 把获取来的菜单传入
        store.commit('setLeftMenu', { menuList: routerToMenu(d.data.routerList[0].children) || [] });
        store.commit('setUser', { info: d.data.userVO || {} });
        store.commit('setRoles', { roles: d.data.roles || [] });
        store.commit('setPermissions', { permissions: d.data.permissions || [] });
        setI18nLanguage(i18n, store.state.locale.key);
        return Promise.resolve();
      }
      return Promise.reject();
    })
    .catch(() => Promise.reject());
};
// 开始登录
const submitLogin = function () {
  // 校验
  userLoginForm.value.validate((valid: any) => {
    if (valid) {
      const loading = ElLoading.service({
        lock: true,
        text: 'loading',
      });
      authApi
        .login(Object.assign(loginForm, { platform: 'web' }))
        .then((d: any) => {
          // hub系统现有接口，code特殊处理
          if (!!d && d.code === 200) {
            store.commit('setToken', d.data);
            store.commit('setRememberme', loginForm);
            Promise.all([getUserInfo()])
              .then(() => {
                router.push('/home');
                loading.close();
              })
              .catch(() => {
                loading.close();
              });
          } else {
            loading.close();
          }
        })
        .catch(() => {
          loading.close();
        });
    }
  });
};
// getCaptchaImg();

const query = router.currentRoute.value.query;
if (query.ACCESS_TOKEN) {
  const loading = ElLoading.service({
    lock: true,
    text: 'loading',
    // background: 'rgba(0, 0, 0, 0.7)',
  });
  store.commit('setToken', { token: query.ACCESS_TOKEN });
  Promise.all([getUserInfo()])
    .then(() => {
      router.push('/home');
      loading.close();
    })
    .catch(() => {
      loading.close();
    });
}
</script>

<style scoped>
.login-title {
  margin-top: 10px;
  margin-bottom: 10px;
  font-size: 30px;
  font-weight: 500;
}
.login-bg {
  width: 100%;
  height: 100%;
  text-align: center;
  background-image: url('../../assets/img/LPHT_BgImg.jpg');
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
}
.login-bg::before {
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  content: '';
}
.codeimg {
  width: 110px;
  margin-left: calc(50% - 110px);
}
.login-btn {
  width: 100%;
  line-height: 38px;
}
.login-row {
  display: inline-block;
  width: 380px;
  padding: 0 15px 15px;
  margin-top: -100px;
  vertical-align: middle;
  background-color: #fff;
  border-radius: 5px;

  /* position: absolute;
    top:50%;
    transform: translateY(-50%); */
}
.remember {
  margin-top: -5px;
  margin-bottom: 10px;
}
:deep(.el-input__inner),
.el-checkbox.el-checkbox--large :deep(.el-checkbox__label),
.login-btn,
.codeimg {
  height: 40px;
  font-size: 14px;
  line-height: 40px;
}
:deep(.el-checkbox__inner)::after {
  top: 2px;
  left: 5px;
}
.el-checkbox.el-checkbox--large :deep(.el-checkbox__inner) {
  width: 16px;
  height: 16px;
}
.el-select {
  width: 100%;
}
.el-footer {
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 40px;
  padding: 0;
  line-height: 40px;
  color: #fff;

  /* background-color: #f0f0f0d0; */
}
.el-footer.beian {
  height: 50px;
  line-height: inherit;
}

@media screen and (max-width: 500px) {
  .login-row {
    width: calc(100% - 30px);
  }
}

@media screen and (min-width: 501px) and (max-width: 900px) {
  .login-row {
    width: 70%;
    min-width: 380px;
    margin-top: 0;
  }
}
</style>
